package com.transaction.simulate.util;
import com.transaction.simulate.mapper.SequenceUtilMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class SequenceUtil {

    private static Logger LOGGER = LoggerFactory.getLogger(SequenceUtil.class);

    public static final String THREE_DIGIT_SEQUENCE = "threeDigitSequence";
    public static final String SIX_DIGIT_SEQUENCE = "sixDigitSequence";

    @Autowired
    private SequenceUtilMapper sequenceUtilMapper;

    /**
     * 获得三位数序列
     * @Title: getThreeDigitSequence
     * @author: dy.yin 2021/8/19 17:16
     */
    public String getThreeDigitSequence() {
        return getSequenceValue(THREE_DIGIT_SEQUENCE,3);
    }

    /**
     * 获得三位数序列
     * @Title: getSixDigitSequence
     * @author: dy.yin 2021/8/23 17:16
     */
    public String getSixDigitSequence() {
        return getSequenceValue(SIX_DIGIT_SEQUENCE,6);
    }

    /**
     * 获得序列的值
     * @Title: getSequenceValue
     * @author: dy.yin 2021/8/19 17:15
     */
    private String getSequenceValue(String sequenceName, int sequenceDigit) {
        String nextValue = "0";
        synchronized (this){
            nextValue = sequenceUtilMapper.getNextValue(sequenceName);
        }
        LOGGER.info("{}获得的序列值为{}",sequenceName,nextValue);
        if(nextValue.length() > sequenceDigit){
            sequenceUtilMapper.resetValue(sequenceName);
            nextValue = "0";
        }
        return nextValue;
    }
}
